package com.smart.community.feign;

import com.smart.community.feign.error.CustomErrorDecoder;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * Feign配置类 配置超时时间、编码器、解码器、日志级别等
 * 注意：Feign模块本身不启用Feign客户端，只提供配置给其他服务使用
 * 
 * @author Wu.Liang
 * @version 2.0.0
 * @since 2024-12-19
 * @updated 2025-08-28 - 添加重试机制和自定义错误解码器
 */
@Configuration
public class FeignConfig {

	/**
	 * 配置编码器
	 */
	@Bean
	Encoder feignEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
		return new SpringFormEncoder(new SpringEncoder(messageConverters));
	}

	/**
	 * 配置解码器
	 */
	@Bean
	Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
		return new SpringDecoder(messageConverters);
	}

	/**
	 * 配置超时时间
	 */
	@Bean
	Request.Options options() {
		return new Request.Options(5, TimeUnit.SECONDS, // 连接超时
				10, TimeUnit.SECONDS, // 读取超时
				true // 重定向
		);
	}

	/**
	 * 配置日志级别
	 */
	@Bean
	Logger.Level feignLoggerLevel() {
		return Logger.Level.BASIC; // 生产环境使用BASIC级别，减少日志输出
	}
	
	/**
	 * 配置重试机制
	 * 重试3次，初始延迟100ms，最大延迟1s
	 */
	@Bean
	Retryer retryer() {
		return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 3);
	}
	
	/**
	 * 配置自定义错误解码器
	 */
	@Bean
	ErrorDecoder errorDecoder() {
		return new CustomErrorDecoder();
	}
}